package cn.mall.auth.controller;

import cn.mall.auth.dto.LoginDTO;
import cn.mall.auth.dto.RegisterDTO;
import cn.mall.auth.service.ILoginService;
import cn.mall.base.utils.AjaxResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 *@Auther:Jarvis
 *@Description:
 */
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private ILoginService iLoginService;


    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 后台登录
     * @param dto
     * @return
     */
    @PostMapping("/login")
    public AjaxResult loginIn(@RequestBody LoginDTO dto){
        try {
            Map<String, Object> loginUser = iLoginService.loginIn(dto);
            return AjaxResult.me().setResultObj(loginUser);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }


    /**
     * 后台登出
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/logout")
    public AjaxResult loginOut(HttpServletRequest httpServletRequest){
        try {
            String token = httpServletRequest.getHeader("token");
            redisTemplate.delete(token);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }

    /**
     * 后台注册
     * @param dto
     * @return
     */
    @PostMapping("/register")
    public AjaxResult managerRegister(@RequestBody RegisterDTO dto){
        try {
            iLoginService.managerRegister(dto);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("用户注册失败" + e.getMessage());
        }
    }

}
